package br.com.massai.model.beans;

import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;

import br.com.massai.model.business.UnitMeasureBusiness;
import br.com.massai.model.entity.UnitMeasure;
import br.com.massai.model.exceptions.ErrorCore;
import br.com.massai.model.exceptions.MessageCore;
import br.com.massai.model.exceptions.SystemException;
import br.com.massai.view.utils.FacesUtil;

@ManagedBean
@ViewScoped
public class UnitMeasureBean extends GenericBean<UnitMeasure> {

	private static final long serialVersionUID = 2742054250025783326L;
	
	private UnitMeasure unitMeasure;

	@EJB private UnitMeasureBusiness unitMeasureBusiness;
	
	public UnitMeasureBean() {
		unitMeasure = new UnitMeasure();
	}

	@Override
	protected UnitMeasure getEntity() {
		return this.unitMeasure;
	}

	@Override
	public String save() throws SystemException {
		boolean isCreate = this.unitMeasure.getId() == null;

		unitMeasureBusiness.save(this.unitMeasure);
		this.unitMeasure = new UnitMeasure();

		if(isCreate) FacesUtil.registrarMensagem(MessageCore.SUCESS_SAVE.getCode());
		else FacesUtil.registrarMensagem(MessageCore.SUCESS_UPDATE.getCode());

		return "unitMeasureRegister?redirect=true";
	}
	
	@Override
	public void delete(UnitMeasure entity) throws SystemException {
		unitMeasureBusiness.delete(entity);
		super.find();
		FacesUtil.registrarMensagem(MessageCore.SUCESS_DELETE.getCode());
	}

	@Override
	public void setParam(String param) throws SystemException {
		try{
			this.param = param;
			if(param != null && !param.isEmpty())
				this.unitMeasure = unitMeasureBusiness.findID(Long.valueOf(param));

		} catch (NumberFormatException e) {
			throw new SystemException(ErrorCore.ERROR_ILLEGAL_ARGUMENT, e);
		} catch (IllegalArgumentException e) {
			throw new SystemException(ErrorCore.ERROR_ILLEGAL_ARGUMENT, e);
		} catch (Exception e) {
			throw new SystemException(ErrorCore.ERROR_UNEXPECTED, e);
		}
	}

	public UnitMeasure getUnitMeasure() {
		return unitMeasure;
	}

	public void setUnitMeasure(UnitMeasure unitMeasure) {
		this.unitMeasure = unitMeasure;
	}
}